<template>
  <div>
    <el-dialog title="详情" :visible.sync="dialogVisible" width="60%" :destroy-on-close="true" :close-on-click-modal="false"
      :close-on-press-escape="false" :before-close="beforeCloseDialog" append-to-body>
      <div style="height: 55vh; overflow-y: scroll">
        <el-collapse v-model="activeName" accordion>
          <el-collapse-item title="实例信息" name="1">
            <div>
              <el-table :data="detailCloudNativeYamlInfo.instanceInfos" style="width: 100%"
                :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center' }" stripe>
                <el-table-column label="实例名称">
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" :content="scope.row.instanceName" placement="bottom-start"
                      popper-class="tooltipClass">
                      <div class="descSpan">
                        {{ scope.row.instanceName }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="host" label="主机地址">
                </el-table-column>
                <el-table-column prop="podIp" label="实例IP"> </el-table-column>
                <el-table-column prop="status" label="状态"> </el-table-column>
                <el-table-column prop="restart" label="重启次数" width="80rem">
                </el-table-column>
                <el-table-column prop="version" label="实例版本" width="80rem">
                </el-table-column>
                <el-table-column prop="containerStatus" label="容器状态" width="80rem">
                  <template slot-scope="scope">
                    <!-- 点击容器状态（比如2/2）时触发弹窗 -->
                    <el-button @click="openContainerDialog()" size="small">
                      {{ scope.row.containerStatus }}
                    </el-button>
                  </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="180">
                  <template slot-scope="scope">
                    <div class="descSpan">
                      {{ scope.row.createTime.split("T")[0] }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template slot-scope="scope">
                    <el-dropdown trigger="click" @command="(command) => {
                      handleCommand(command, scope.row);
                    }
                      ">
                      <el-button type="text" size="mini">
                        更多<i class="el-icon-arrow-down el-icon--right"></i>
                      </el-button>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="showLogs">查看日志
                        </el-dropdown-item>
                        <el-dropdown-item command="execContainer">进入容器
                        </el-dropdown-item>
                        <el-dropdown-item command="deletePod">删除实例
                        </el-dropdown-item>
                        <el-dropdown-item command="event">事件
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
          <el-collapse-item title="端口信息" name="2">
            <div v-for="(portInfo, index) in detailCloudNativeYamlInfo.portInfos" :key="portInfo.port"
              style="margin-bottom: 5px">
              <el-row>
                <el-col :span="4">
                  <span> 协议： </span>
                  <el-input :disabled="true" style="width: 80px" v-model="portInfo.protocol" size="mini">
                  </el-input>
                </el-col>
                <el-col :span="4">
                  <span> 内部端口： </span>
                  <el-input style="width: 80px" v-model="portInfo.port" disabled size="mini">
                  </el-input>
                </el-col>
                <el-col :span="6">
                  <span> 暴露端口： </span>
                  <el-input style="width: 80px" v-show="!portInfo.fixed" disabled size="mini" placeholder="随机端口">
                  </el-input>
                  <el-input style="width: 80px" v-model="portInfo.expose" v-show="portInfo.fixed" disabled size="mini">
                  </el-input>
                </el-col>
                <!--                <el-col :span="3">-->
                <!--                  <el-switch-->
                <!--                    active-text="开启域名"-->
                <!--                    v-model="portInfo.enableDns"-->
                <!--                    disabled-->
                <!--                  >-->
                <!--                  </el-switch>-->
                <!--                </el-col>-->
                <el-col :span="7" v-show="portInfo.enableDns">
                  <span> DNS： </span>
                  <el-input style="width: 120px" v-model="portInfo.dns" size="mini" disabled>
                  </el-input>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
          <el-collapse-item title="资源需求" name="5" v-if="null !== detailCloudNativeYamlInfo.resourceInfo">
            <div>
              <el-row>
                <el-col :span="9">
                  <div style="margin-bottom: 5px">
                    <span> CPU预留： </span>
                    <el-input style="width: 250px" v-model="detailCloudNativeYamlInfo.resourceInfo.cpuRequest
                      " controls-position="right" :min="0.1" :max="256" :step="0.1" type="number" size="mini" disabled>
                      <template v-slot:append>核</template>
                    </el-input>
                  </div>
                  <div v-show="detailCloudNativeYamlInfo.resourceInfo.enableLimit">
                    <span> CPU限制： </span>
                    <el-input style="width: 250px" v-model="detailCloudNativeYamlInfo.resourceInfo.cpuLimit"
                      controls-position="right" :min="0.1" :max="256" :step="0.1" type="number" size="mini" disabled>
                      <template v-slot:append>核</template>
                    </el-input>
                  </div>
                </el-col>
                <el-col :span="9">
                  <div style="margin-bottom: 5px">
                    <span> 内存预留： </span>
                    <el-input style="width: 250px" v-model="detailCloudNativeYamlInfo.resourceInfo.memRequest
                      " controls-position="right" :min="4" :max="16384" :step="256" type="number" size="mini" disabled>
                      <template v-slot:append>MB</template>
                    </el-input>
                  </div>
                  <div v-show="detailCloudNativeYamlInfo.resourceInfo.enableLimit">
                    <span>内存限制： </span>
                    <el-input style="width: 250px" v-model="detailCloudNativeYamlInfo.resourceInfo.memLimit"
                      controls-position="right" :min="4" :max="16384" :step="256" type="number" size="mini" disabled>
                      <template v-slot:append>MB</template>
                    </el-input>
                  </div>
                </el-col>
                <el-col :span="6">
                  <el-switch v-model="detailCloudNativeYamlInfo.resourceInfo.enableLimit" active-color="#13ce66"
                    inactive-color="#ff4949" disabled :active-text="resourceLimitText"
                    @change="changeResourceLimitStatus">
                  </el-switch>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
          <el-collapse-item title="事件信息" name="3">
            <div>
              <el-table :data="detailCloudNativeYamlInfo.eventInfos" style="width: 100%"
                :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center' }" stripe>
                <el-table-column prop="type" label="事件类型" width="120rem">
                </el-table-column>
                <el-table-column prop="reason" label="事件原因" width="160rem">
                </el-table-column>
                <el-table-column prop="note" label="事件详情">
                </el-table-column>
                <el-table-column prop="time" label="事件时间" width="180rem">
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
          <el-collapse-item title="操作信息" name="4">
            <div>
              <el-table :data="detailCloudNativeYamlInfo.operateInfos" style="width: 100%"
                :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center' }" stripe>
                <el-table-column prop="userName" label="用户名称" width="120rem">
                </el-table-column>
                <el-table-column prop="targetName" label="目标名称" width="160rem">
                </el-table-column>
                <el-table-column prop="targetType" label="目标类型">
                  <template slot-scope="scope">
                    {{ getOperationType(scope.row.targetType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="operatorIp" label="操作IP">
                </el-table-column>
                <el-table-column label="日志信息">
                  <template slot-scope="scope">
                    <el-tooltip effect="dark" :content="scope.row.logInfo" placement="bottom" popper-class="tooltipClass">
                      <div class="descSpan" style="text-align: left">
                        {{ scope.row.logInfo }}
                      </div>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column prop="appType" label="应用类型">
                  <template slot-scope="scope">
                    {{ getAppType(scope.row.appType) }}
                  </template>
                </el-table-column>
                <el-table-column prop="updateTime" label="创建时间" width="180rem">
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <div v-if="showEventDetail">
        <el-dialog title="事件信息" :append-to-body="true" :close-on-press-escape="false" :close-on-click-modal="false"
          :destroy-on-close="true" :visible.sync="showEventDetail" style="z-index: 10000">
          <div style="height: 45vh; overflow-y: auto">
            <el-table :data="tableData" style="width: 100%" :cell-style="{ textAlign: 'center' }"
              :header-cell-style="{ textAlign: 'center' }">
              <el-table-column prop="type" label="类型" width="90">
              </el-table-column>
              <el-table-column prop="reason" label="原因" width="90">
              </el-table-column>
              <el-table-column prop="note" label="详情"></el-table-column>
              <el-table-column prop="time" label="时间" width="190">
              </el-table-column>
            </el-table>
          </div>
        </el-dialog>
      </div>
      <!--      <div class="deployButtonDiv">-->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" class="el-button-primary-style" @click="beforeCloseDialog(null)">
          关 闭
        </el-button>
      </span>
      <!--      </div>-->
    </el-dialog>
    <el-dialog :visible.sync="showLogDialog" title="容器选择" @close="handleCancel" :width="'400px'" class="dialog-center">
      <div class="select-container">
        <el-select v-model="selectedContainerName" placeholder="请选择一个容器" class="center-select">
          <el-option v-for="container in containers" :key="container.name" :label="container.name"
            :value="container.name" />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleLogCancel">取消</el-button>
        <el-button type="primary" @click="handleLogConfirm">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="showExecDialog" title="容器选择" @close="handleCancel" :width="'400px'" class="dialog-center">
      <div class="select-container">
        <el-select v-model="selectedContainerName" placeholder="请选择一个容器" class="center-select">
          <el-option v-for="container in containers" :key="container.name" :label="container.name"
            :value="container.name" />
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleExecCancel">取消</el-button>
        <el-button type="primary" @click="handleExecConfirm">确定</el-button>
      </span>
    </el-dialog>
    <!-- 容器详情弹窗 -->
    <!-- 容器详情弹窗 -->
    <el-dialog title="容器详情" :visible.sync="dialogContainerDetailsVisible" width="40%">
      <el-table :data="selectedContainerDetails" style="width: 100%">
        <el-table-column prop="name" label="容器名称"></el-table-column>
        <el-table-column prop="image" label="镜像名称"></el-table-column>
        <el-table-column prop="restartCount" label="重启次数"></el-table-column>
        <el-table-column prop="started" label="是否启动">
          <template slot-scope="scope">
            <el-tag :type="scope.row ? 'true' : 'false'">
              {{ scope.row ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogContainerDetailsVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTenantId } from "@/utils/tenantId";
export default {
  name: "DetailYamlInfo",
  props: ["tmpCloudNative"],
  data() {
    return {
      dialogVisible: false,
      activeName: "1",
      namespace: "",
      podName: "",
      tableData: [],
      deleteInfo: {
        namespace: "",
        podName: "",
      },
      showEventDetail: false,
      detailCloudNativeYamlInfo: {
        resourceInfo: {},
        instanceInfos: [],
        portInfos: {},
        operateInfos: [],
        eventInfos: [],
      },
      resourceLimitText: "开启资源限制",
      showLogDialog: false,  // 控制日志弹窗显示
      selectedContainerName: '',  // 存储选择的容器名称
      containers: [],  // 存储容器信息
      showExecDialog: false,  // 控制进入容器弹窗显示
      dialogContainerDetailsVisible: false,   // 控制弹窗显示
      selectedContainerDetails: []   // 存储选中的容器详细信息
    };
  },
  methods: {
    detailCloudNative() {
      this.$appManageApi.detailCloudYaml(this.tmpCloudNative.id).then((res) => {
        if (res && res.code === 200) {
          this.detailCloudNativeYamlInfo = res.data;
          this.podName =
            this.detailCloudNativeYamlInfo.instanceInfos[0].instanceName;
          this.$tenantManageApi
            .getTenantNameById(getTenantId())
            .then((response) => {
              // console.log("response", response);
              this.namespace = response.data;
            })
            .catch((error) => {
              console.error(error);
            });
          if (this.detailCloudNativeYamlInfo.resourceInfo !== null) {
            if (this.detailCloudNativeYamlInfo.resourceInfo.enableLimit) {
              this.resourceLimitText = "开启资源限制";
            } else {
              this.resourceLimitText = "关闭资源限制";
            }
          }
        }
      });
    },
    beforeCloseDialog(done) {
      this.$emit("closeDetailCloudNative");
      this.dialogVisible = false;
      this.activeName = "1";
      this.detailCloudNativeYamlInfo = {
        resourceInfo: {},
        instanceInfos: [],
        portInfos: {},
        operateInfos: [],
        eventInfos: [],
      };
      if (done !== null) {
        done();
      }
    },
    //更多操作
    handleCommand(command, row) {
      console.log("command", command, "row", row);
      if (command === "showLogs") {
        this.showLogsInfo(row);
      } else if (command === "execContainer") {
        this.execContainer(row);
      } else if (command === "deletePod") {
        this.deleteDeployInfo();
      } else if (command === "event") {
        this.showEventInfo(row);
      }
    },
    showLogsInfo(row) {
      const logsInfo = {
        namespace: this.namespace,
        podName: row.instanceName,
        podIp: row.podIp,
      };
      console.log("logsInfo", logsInfo);
      this.$appManageApi.viewPodLogs(logsInfo).then((res) => {
        if (res && res.code === 200) {
          console.log("res.data", res.data);
          if (res.data.length === 1) {
            // 如果数组长度为1，直接打开showLogsUrl
            window.open(res.data[0].showLogsUrl);
          } else if (res.data.length > 1) {
            // 如果数组长度大于1，弹出选择窗口
            this.containers = res.data;  // 更新容器数据
            this.showLogDialog = true;  // 显示弹窗
          }
        }
      });
    },
    handleLogConfirm() {
      const selectedContainer = this.containers.find(
        (container) => container.name === this.selectedContainerName
      );
      if (selectedContainer) {
        // 打开选中的容器的 showLogsUrl
        window.open(selectedContainer.showLogsUrl);
        this.showLogDialog = false;  // 关闭弹窗
      } else {
        this.$message.error('未找到所选容器');
      }
    },
    handleLogCancel() {
      this.showLogDialog = false;  // 取消选择，关闭弹窗
    },
    execContainer(row) {
      const podInfo = {
        podIp: row.podIp,
        namespace: this.namespace,
        podName: row.instanceName,
      };
      console.log("podInfo", podInfo);
      this.$appManageApi.execPodContainer(podInfo).then((res) => {
        if (res && res.code === 200) {
          console.log("res.data", res.data);
          if (res.data.length === 1) {
            // 如果数组长度为1，直接打开execUrl
            window.open(res.data[0].execUrl);
          } else if (res.data.length > 1) {
            // 如果数组长度大于1，弹出选择窗口
            this.containers = res.data;  // 更新容器数据
            this.showExecDialog = true;  // 显示弹窗
          }
        }
      });
    },
    handleExecConfirm() {
      const selectedContainer = this.containers.find(
        (container) => container.name === this.selectedContainerName
      );
      if (selectedContainer) {
        // 打开选中的容器的 execUrl
        window.open(selectedContainer.execUrl);
        this.showExecDialog = false;  // 关闭弹窗
      } else {
        this.$message.error('未找到所选容器');
      }
    },
    handleExecCancel() {
      this.showExecDialog = false;  // 取消选择，关闭弹窗
    },
    deleteDeployInfo() {
      this.deleteInfo.namespace = this.namespace;
      this.deleteInfo.podName = this.podName;
      console.log("deleteInfo", this.deleteInfo);
      this.$appManageApi.deleteDeploy(this.deleteInfo).then((res) => {
        if (res && res.code === 200) {
          setTimeout(() => {
            this.$message.success(res.data);
            this.detailCloudNative();
          }, 1000);
        }
      });
    },

    showEventInfo(row) {
      this.showEventDetail = true;
      this.deleteInfo.namespace = this.namespace;
      this.deleteInfo.podName = row.instanceName;
      this.$appManageApi.getEventInfo(this.deleteInfo).then((res) => {
        if (res && res.code === 200) {
          this.tableData = res.data;
        }
      });
    },
    getAppType(operateTarget) {
      const statusMap = {
        0: "资源管理中心",
        1: "应用商店",
        2: "容器管理平台",
      };
      return statusMap[operateTarget] || "未知类型";
    },
    changeResourceLimitStatus(status) {
      if (status) {
        this.resourceLimitText = "开启资源限制";
      } else {
        this.resourceLimitText = "关闭资源限制";
      }
    },
    getOperationType(operateTarget) {
      const statusMap = {
        0: "认证操作",
        1: "添加操作",
        2: "删除操作",
        3: "修改操作",
        4: "服务实例操作",
        5: "服务组实例操作",
        6: "云原生实例操作",
      };
      return statusMap[operateTarget] || "未知类型";
    },
    // 打开容器详情弹窗
    openContainerDialog() {
      // 获取容器的详细信息
      const podIp = this.detailCloudNativeYamlInfo.instanceInfos[0].podIp;
      console.log("podIp", podIp);
      this.$appManageApi.detailCloudYamlContainer(podIp).then((res) => {
        if (res && res.code === 200) {
          // this.containerDetails = res.data;
          this.selectedContainerDetails = res.data;  // 设置容器的详细信息
          this.dialogContainerDetailsVisible = true;                          // 打开弹窗
        } else {
          this.dialogContainerDetailsVisible = false;
          this.$message.error(res.msg);
        }
      });
    }
  },
  beforeMount() {
    this.detailCloudNative();
  },
};
</script>

<style scoped>
.dialog-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.select-container {
  display: flex;
  justify-content: center;
  width: 100%;
}

.center-select {
  width: 60%;
  /* 调整宽度以适应布局 */
}
</style>
